<?php
namespace app\single\controller;
use jwt\Jwt;
/**
 * #Vip接口 {用户购买会员接口}
 */
class Vip extends Common{
    /**
     * 获取VIP列表
     * @return [type] [description]
     */
    function index(){
        $uid=$this->user['id'];
        //$user=model('member')->read(['id'=>$uid],'vip_level');
        $module=model('artmodule')->read(['name'=>request()->module()],'id');
        $map=[
            'status'=>1,
            //'level'=>['level','>=',$user['vip_level']],
            'money'=>['money','>',0],
        ];
        if(isset($module['id'])){
            $map['module_id']=$module['id'];
        }
        $list=model($this->table)->readAll($map,0,[
            'order'=>'sort',
            'field'=>'id,name,remark,money,raw_money,level,ratio,label,id<0 as cid,id<0 as c_money'
        ]);
        $coupon=controller('coupon')->memberCoupon();
        if(is_string($coupon)){
            $coupon=json_decode($coupon,true);
        }
        if($coupon['status']===0&&!empty($coupon['data'])){
            foreach ($list as $k => $v) {
                foreach ($coupon['data'] as $c) {
                    if($v['money']>=$c['usable']&&$v['c_money']<$c['value']){
                        $v['cid']=$c['id'];
                        $v['c_money']=$c['value'];
                        $list[$k]=$v;
                    }
                }
            }
        }
        return json('',0,$list);
    }
    /**
     * 购买VIP（暂未限定vip类型，比如买了黑钻之后，买月钻，比例不相同问题）
     * @param  integer $vid vipID
     * @param  integer $cid 优惠卷列表memberCoupon 返回的ID
     * @param  string  $pay_type 支付方式（alipay、weixinpay）
     * @return [type]       [description]
     */
    function buy($vid=0,$cid=0,$pay_type='alipay'){
        $pay_types=['alipay','weixinpay'];
        if(!in_array($pay_type, $pay_types)){
            return json('不支持的支付方式',1);
        }
        if($vid<=0){
            return json('该VIP可能已经删除',1);
        }
        $map=[
            'id'=>$vid,
            'status'=>1,
        ];
        $module=model('artmodule')->read(['name'=>request()->module()],'id');
        if(isset($module['id'])){
            $map['module_id']=$module['id'];
        }
        $has=model($this->table)->read($map,'id,name,money,ratio,y,m,d,level');
        if(empty($has)){
            return json('该VIP可能已经关闭',1);
        }
        $uid=$this->user['id'];
        $user=model('member')->read(['id'=>$uid],'id,vip_level,pid,tel,vip_trial');
        if($user['vip_level']>$has['level']){
            return json('暂不允许购买比您当前级别低的VIP级别',1);
        }
        if($user['vip_trial']>0&&$has['money']==0){
            return json('每个用户仅允许购买一次试用套餐哦',1);
        }
        if($user['vip_level']>0&&$has['money']==0){
            return json('您已经是VIP不允许购买该套餐',1);
        }
        // 增加的时长（单位：s）
        $overTime=addDuration($has['y'],$has['m'],$has['d'],true);
        
        $time=time();
        $map=[
            'uid'=>$uid,
            'status'=>1,
            'e_time'=>['e_time','>=',$time],
            'usable'=>['usable','<=',$has['money']],
        ];
        if($cid>0){
            $map['id']=$cid;
        }
        $coupon=model('memberCoupon')->read($map,'id,cid,value');
        
        // 生成订单
        $number=model('order')->number();
        $data=[
            'uid'=>$uid,
            'pid'=>$user['pid'],
            'tel'=>$user['tel'],
            's_time'=>$time,
            'expire_time'=>time()+(60*86400), //到期时间2个月
            'number'=>$number,
            'vid'=>$has['id'],
            'vip_level'=>$has['level'],
            'cid'=>0,
            'coupon_money'=>0, //优惠卷低扣金额
            'money'=>$has['money'], //用户付款金额
            'raw_money'=>$has['money'],
            'ratio'=>$has['ratio'],
            'time'=>$overTime,
            'pay_type'=>$pay_type,
        ];
        if(isset($coupon['value'])&&$coupon['value']>0){
            $data['mcid']=$coupon['id'];
            $data['cid']=$coupon['cid'];
            $data['coupon_money']=$coupon['value'];
            $data['money']-=$coupon['value'];
        }
        $add=model('order')->add($data);

        if($add){
            if($data['raw_money']==0){
                $rs=model('order')->orderHandle($data['number'],$data['number'],$data['raw_money'],'VIP试用套餐');
                if(true!==$rs){
                    return $rs;
                }
                model('member')->where(['id'=>$uid])->setInc('vip_trial');
                logger('info',lang('user create order',[
                    'VIP试用',
                    $user['tel'],
                    $data['money'],
                    'VIP试用',
                    'VIP试用套餐',
                ]));
                return json('VIP试用套餐购买成功',1);
            }elseif($pay_type==='alipay'){
                $_alidata=[
                    'subject'=>$has['name'],
                    'out_trade_no'=>$data['number'],
                    'total_amount'=>$data['money'],
                ];
                
                if($user['tel']==='18777148293'){ //测试用户
                    $_alidata['total_amount']=0.01;
                }
                $res=alipay($_alidata);
                logger('info',lang('user create order',[
                    'VIP',
                    $user['tel'],
                    $data['money'],
                    '支付宝',
                    $has['name'],
                ]));
                return json('订单创建成功',0,['number'=>$res]);
            }elseif($pay_type==='weixinpay'){
                $res=weixinpay([
                    'body'=>$has['name'],
                    'out_trade_no'=>$data['number'],
                    'total_fee'=>$data['money']*100, //单位：分
                ]);
                if($res['success']){
                    $res_data=$res['data'];
                    $res_data['wx_package']=$res_data['package'];
                    unset($res_data['package']);
                    $res_data['order_number']=$data['number'];
                    logger('info',lang('user create order',[
                        'VIP',
                        $user['tel'],
                        $data['money'],
                        '微信',
                        $has['name'],
                    ]));
                    return json('订单创建成功',0,$res_data);
                }
                
                return json($res['msg'],1);
            }else{
                return json('不支持的支付方式',1);
            }
            
        }
        return json('系统繁忙订单创建失败',1);
        
    }
    /**
     * 付款成功后通过该接口获取验证用户是否付款
     * 该接口将返回一个新的token以及数据，前端应该替换
     * @param  string $number 订单编号
     * @return [type]         [description]
     */
    function buyResult($number=''){
        $e=Jwt::decode($number);
        if(!$e['success']||!isset($e['data'])){
            return json('订单数据有误',1);
        }
        $uid=$this->user['id'];
        $order=model('order')->read(['number'=>$e['data'],'uid'=>$uid]);
        if(empty($order)){
            return json('订单不存在',1);
        }
        if($order['state']){
            $rs=model('member')->read(['id'=>$uid],'id,vip_expire,vip_ratio,vip_level')->append('vip_text');
            return json('订单支付成功',0,[
                "vip_expire"=>$rs['vip_expire'],
                "vip_ratio"=>$rs['vip_ratio'],
                "vip_level"=>$rs['vip_level'],
                "vip_text"=>$rs['vip_text'],
            ]);
        }
        return json('订单未支付',1);
    }

    
}